package com.hexu.event.dao;

import com.hexu.event.entity.Specie;
import com.hexu.event.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ArticleSpecieDao {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    //增加文章种类
    public boolean addSpecie(Specie specie){
        String sql = "insert into article_specie(name)"
                + " values (?)";
        try {
            conn = JdbcUtil.getConn();
            ps = conn.prepareStatement(sql);
            //Base64 加密
            //View层set的数据
            ps.setString(1, specie.getName());
            ps.executeUpdate();

            //添加成功
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            JdbcUtil.close(conn, ps, null);
        }
        //添加失败
        return false;
    }

    //删除文章种类
    public boolean deleteSpecie(String name){
        String sql="delete from article_specie where name=?";
        try {
            conn = JdbcUtil.getConn();
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            if(ps.executeUpdate()>0){
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(conn, ps, null);
        }
        return false;
    }

    //返回所有种类
    public List<Specie> getSpecie(){
        String sql = "select * from article_specie";
        try {
            conn = JdbcUtil.getConn();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            List<Specie> specieList = new ArrayList<>();
            while (rs.next()){
                Specie specie = new Specie();
                specie.setId(rs.getInt("id"));
                specie.setName(rs.getString("name"));
                specieList.add(specie);
            }
            return specieList;

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.close(conn, ps, rs);
        }
        return null;
    }
}
